package com.hzncc.flowable_diboot.contract.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.S;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.file.util.HttpHelper;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.util.IamSecurityUtils;
import com.hzncc.flowable_diboot.constans.PermissionCons;
import com.hzncc.flowable_diboot.contract.dto.ContractAuditDTO;
import com.hzncc.flowable_diboot.contract.entity.ContractAudit;
import com.hzncc.flowable_diboot.contract.entity.ContractProduct;
import com.hzncc.flowable_diboot.contract.entity.ContractProductMaterial;
import com.hzncc.flowable_diboot.contract.service.ContractAuditService;
import com.hzncc.flowable_diboot.contract.service.ContractProductService;
import com.hzncc.flowable_diboot.contract.service.SalesContractService;
import com.hzncc.flowable_diboot.contract.service.impl.OaInterfaceService;
import com.hzncc.flowable_diboot.contract.vo.*;
import com.hzncc.flowable_diboot.enums.ContractAuditStatusEnum;
import com.hzncc.flowable_diboot.enums.ContractAuditTypeEnum;
import com.hzncc.flowable_diboot.enums.OAStatusEnum;
import com.hzncc.flowable_diboot.enums.SAPStatusEnum;
import com.hzncc.flowable_diboot.excel.listener.ContractProductMaterialImportListener;
import com.hzncc.flowable_diboot.excel.model.ContractProductMaterialImportModel;
import com.hzncc.flowable_diboot.excel.service.MultiSheetExcelImportService;
import com.hzncc.flowable_diboot.interfacelog.annotation.InterfaceLog;
import com.hzncc.flowable_diboot.project_contracts.service.ProjectContractAuditService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;

import jakarta.annotation.Resource;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 合同审批 相关rest接口
 *
 * @author MyName
 * @version 1.0
 * @date 2024-07-12
 * Copyright © MyCorp
 */
@Log4j2
@RequestMapping("/contract-audit")
@BindPermission(name = "合同审批")
@RestController
public class ContractAuditController extends BaseCrudRestController<ContractAudit> {

    @Autowired
    private ContractAuditService contractAuditService;

    @Resource
    private MultiSheetExcelImportService multiSheetExcelImportService;

    @Autowired
    private OaInterfaceService oaInterfaceService;

    @Autowired
    private ProjectContractAuditService projectContractAuditService;

    @Autowired
    private ContractProductService contractProductService;

    @Autowired
    private SalesContractService salesContractService;

    //@GetMapping(value = "/oaa/{id}")
    //public String testOA(@PathVariable String id) {
    //    // test
    //    pushOa(id);
    //    return "ok";
    //}

    /**
     * OA合同评审回传
     *
     * @param objectid 合同评审id
     * @param result   oa评审结果
     * @param bdCode
     * @return
     * @throws Exception
     */
    @InterfaceLog(code = "OA_RESP_AUDIT_STATUS", name = "OA合同审批状态回传", direction = "OA -> CRM")
    @PostMapping("/oa/auditStatus")
    public JsonResult<String> receiveOaApprovalAuditResults(String objectid, String result, String bdCode) throws Exception {
        if (S.contains(bdCode, "sys")) {
            return contractAuditService.receiveOaApprovalAuditResults(objectid, result, bdCode);
        } else if (S.contains(bdCode, "proj") || S.contains(bdCode, "sam")) {
            return projectContractAuditService.receiveOaApprovalAuditResults(objectid, result, bdCode);
        }
        JsonResult<String> jsonResult = new JsonResult<>();
        jsonResult.setCode(500);
        jsonResult.setMsg("未知的bdCode[" + bdCode + "]");
        return jsonResult;
    }


    @InterfaceLog(code = "OA_RESP_ES_STATUS", name = "OA教育状态回传", direction = "OA -> CRM")
    @PostMapping("/oa/esStatus")
    public JsonResult<String> receiveOaApprovalEs(@RequestBody EsRespVO respVO) throws Exception {
        // todo
        JsonResult<String> jsonResult = new JsonResult<>();
        jsonResult.setCode(200);
        jsonResult.setMsg("操作成功");
        return jsonResult;
    }

    @InterfaceLog(code = "OA_RESP_IS_STATUS", name = "OA智能产线状态回传", direction = "OA -> CRM")
    @PostMapping("/oa/isStatus")
    public JsonResult<String> receiveOaApprovalIs(@RequestBody IsRespVO respVO) throws Exception {
        // todo
        JsonResult<String> jsonResult = new JsonResult<>();
        jsonResult.setCode(200);
        jsonResult.setMsg("操作成功");
        return jsonResult;
    }

    /**
     * 查询合同待办
     *
     * @return
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/contract-todo")
    public JsonResult<?> getContractTodo() {
        List<ContractAuditTaskVO> contractTodo = contractAuditService.getContractTodo();
        return JsonResult.OK(contractTodo);
    }

    /**
     * 处理合同待办
     *
     * @param contractAuditTaskVO
     * @return
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/approve-contract")
    public JsonResult<?> approveContractAudit(@RequestBody ContractAuditTaskVO contractAuditTaskVO) {
        contractAuditService.approveContract(contractAuditTaskVO);
        return JsonResult.OK();
    }

    /**
     * 导入技术清单
     *
     * @return
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/import-material")
    public JsonResult<?> importProductMaterialExcel(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
        String sheetNo = (String) params.get("sheetNo");
        if (sheetNo == null) {
            return JsonResult.FAIL_EXCEPTION("请选择要上传的清单页");
        }
        List<ContractProductMaterialImportModel> list = multiSheetExcelImportService.readSheet(file, ContractProductMaterialImportModel.class, ContractProductMaterialImportListener.class, 5, sheetNo);
        // 添加行号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i+1+"");
        }
        list = list.stream().filter(e -> e.getMaterialPrice() != null && e.getRowNum() != null).peek(e -> e.setRowNum(new BigDecimal(e.getRowNum()).multiply(BigDecimal.TEN).toString())).collect(Collectors.toList());
        List<ContractProductMaterial> result = BeanUtils.convertList(list, ContractProductMaterial.class);
        return JsonResult.OK(result);
    }

    /**
     * 导入技术清单
     *
     * @return
     */
    @PostMapping("/import-tech")
    public JsonResult<?> importTechList(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws IOException {
        String sheetNo = (String) params.get("sheetNo");
        if (sheetNo == null) {
            return JsonResult.FAIL_EXCEPTION("请选择要上传的清单页");
        }
//        Map<String, List<Integer>> targetCell = Map.of("contractCode",Arrays.asList(0,4),"model",Arrays.asList(1,0));
        Map<String, String> res = new HashMap<>();
        String contractCode = multiSheetExcelImportService.readCell(file, 1, 5, sheetNo);
        String model = multiSheetExcelImportService.readCell(file, 2, 1, sheetNo);
        res.put("contractCode", contractCode.split("：")[1]);
        String[] split = model.substring(model.indexOf("：") + 1).split("/");
        res.put("machineModel", String.join("/", split[0], split[1]));
        res.put("numberOfAxes", split[2]);
        res.put("numberOfChannels", split[3]);
        return JsonResult.OK(res);
    }


    /**
     * 合同归档
     *
     * @param contractAuditIds
     * @return
     */
    @Log(operation = PermissionCons.CONTRACT_ARCHIVE_LABEL)
    @BindPermission(name = PermissionCons.CONTRACT_ARCHIVE_LABEL, code = PermissionCons.CONTRACT_ARCHIVE)
    @PostMapping("/archive")
    public JsonResult<?> archiveContract(@RequestBody List<String> contractAuditIds) {
        contractAuditService.archiveContract(contractAuditIds);
        return JsonResult.OK();
    }

    /**
     * 归档合同取消
     *
     * @param contractAuditIds 合同评审id
     * @return
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/archiveCancel")
    public JsonResult<?> archiveCancel(@RequestBody List<String> contractAuditIds) {
        contractAuditService.cancelArchive(contractAuditIds);
        return JsonResult.OK();
    }

    /**
     * 复制合同
     *
     * @param contractAuditId
     * @return
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/copy/{contractAuditId}")
    public JsonResult<?> copyContractAudit(@PathVariable("contractAuditId") String contractAuditId) {
        ContractAuditVO contractAuditVO = contractAuditService.copyContractDetail(contractAuditId);
        return JsonResult.OK(contractAuditVO);
    }

    /**
     * 分页查询合同审批列表
     *
     * @param reqVO
     * @param pagination
     * @return
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/page")
    public JsonResult<?> getContractPage(ContractAuditDTO reqVO, String type, String permission, Pagination pagination) throws Exception {
        return contractAuditService.selectContract(reqVO, type, permission, pagination);
    }

    /**
     * 查询合同审批详情
     *
     * @param contractAuditId
     * @return
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/detail/{contractAuditId}")
    public JsonResult<?> getContractDetail(@PathVariable("contractAuditId") String contractAuditId) {
        ContractAuditVO contractAuditVO = contractAuditService.getContractDetail(contractAuditId);
        return JsonResult.OK(contractAuditVO);
    }

    /**
     * @param contractCode
     * @return
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/detail-by-code/{contractCode}")
    public JsonResult<?> getContractDetailByCode(@PathVariable("contractCode") String contractCode) {
        ContractAuditVO contractAuditVO = contractAuditService.getContractDetailByCode(contractCode);
        return JsonResult.OK(contractAuditVO);
    }

    /**
     * 保存合同评审
     *
     * @param contractAuditVO
     * @return
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/save")
    public JsonResult<?> saveContractAudit(@RequestBody ContractAuditVO contractAuditVO) {
        contractAuditVO.setContractStatus(ContractAuditStatusEnum.NO_SUBMIT.getCode());
        String contractAuditId = contractAuditService.saveContractAudit(contractAuditVO);
        return JsonResult.OK(contractAuditId);
    }

    /**
     * 删除合同评审
     *
     * @param contractAuditId
     * @return
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_DELETE)
    @DeleteMapping("/delete-save/{contractAuditId}")
    public JsonResult<?> deleteContractAudit(@PathVariable("contractAuditId") String contractAuditId) {
        contractAuditService.deleteContractAudit(contractAuditId);
        return JsonResult.OK();
    }

    /**
     * 提交合同评审
     *
     * @param contractAuditVO
     * @return
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/submit")
    public JsonResult<?> submitContractAudit(@RequestBody ContractAuditVO contractAuditVO) {
        if (contractAuditVO.getIsAudit() == null) {
            contractAuditVO.setIsAudit(true);
        }
        if (!S.equals(contractAuditVO.getBusinessModel(), "IPL") && contractAuditVO.getContractProductVOList().stream().anyMatch(e -> e.getProductDiscount() == null)) {
            return JsonResult.FAIL_VALIDATION("产品折扣不能为空");
        }
        contractAuditVO.setContractStatus(ContractAuditStatusEnum.PROCESSING.getCode());
        String contractAuditId = contractAuditService.submitContractAudit(contractAuditVO);
        if (!contractAuditVO.getIsAudit()) {
            contractAuditVO.setContractStatus(ContractAuditStatusEnum.SUPPLEMENTARY_TECHNOLOGY_LIST.getCode());
            contractAuditService.updateEntity(contractAuditVO);
            return JsonResult.OK();
        }
        new Thread(() -> {
            pushOa(contractAuditId);
        }).start();
        return JsonResult.OK(contractAuditId);
    }

    /**
     * 保存合同变更评审
     *
     * @param contractAuditVO
     * @return
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/save-update")
    public JsonResult<?> saveContractAuditUpdate(@RequestBody ContractAuditVO contractAuditVO) {
        contractAuditVO.setContractStatus(ContractAuditStatusEnum.NO_SUBMIT.getCode());
        contractAuditVO.getContractAuditUpdateVO().setSubmit(false);
        contractAuditVO.getContractExtVO().setSupplierSignTime(LocalDateTime.now());
        contractAuditVO.getContractExtVO().setBuyerSignTime(LocalDateTime.now());
        return JsonResult.OK(contractAuditService.saveContractAuditUpdate(contractAuditVO));
    }

    /**
     * 删除合同变更评审
     *
     * @param contractAuditId
     * @return
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/delete-update/{contractAuditId}")
    public JsonResult<?> deleteContractAuditUpdate(@PathVariable("contractAuditId") String contractAuditId) {
        contractAuditService.deleteContractAuditUpdate(contractAuditId);
        return JsonResult.OK();
    }

    /**
     * 提交合同变更评审
     *
     * @param contractAuditVO
     * @return
     */
    @Log(operation = PermissionCons.CONTRACT_CHANGE_LABEL)
    @BindPermission(name = PermissionCons.CONTRACT_CHANGE_LABEL, code = PermissionCons.CONTRACT_CHANGE)
    @PostMapping("/submit-update")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<?> submitContractAuditUpdate(@RequestBody ContractAuditVO contractAuditVO) {
        if (contractAuditVO.getContractProductVOList() == null) {
            return JsonResult.FAIL_VALIDATION("合同产品不能为空");
        }
        if (contractAuditVO.getContractProductVOList().stream().anyMatch(e -> S.equals(e.getSapContractPushStatus(), "1") && S.isNotBlank(e.getSapContractCode())) && S.equals(contractAuditVO.getSapStatus(), SAPStatusEnum.NO.getCode())) {
            return JsonResult.FAIL_VALIDATION("请先将合同变更推送到SAP");
        }
        contractAuditVO.getContractAuditUpdateVO().setSubmit(true);
        contractAuditVO.getContractExtVO().setSupplierSignTime(LocalDateTime.now());
        contractAuditVO.getContractExtVO().setBuyerSignTime(LocalDateTime.now());
        String id = contractAuditService.submitContractAuditUpdate(contractAuditVO);
        if (!contractAuditVO.getIsAudit()) {
            contractAuditVO.setContractStatus(ContractAuditStatusEnum.SUPPLEMENTARY_TECHNOLOGY_LIST.getCode());
            contractAuditService.updateEntity(contractAuditVO);
            // 免审批情况下直接更新sap合同状态
            List<ContractProductListVO> contractProductVOList = contractAuditVO.getContractProductVOList();
            if (contractProductVOList != null) {
                contractAuditService.updateSapStatus(contractProductVOList.stream().map(ContractProduct::getId).toList());
            }
            return JsonResult.OK();
        }
        if (contractAuditVO.getContractAuditUpdateVO().getAddMaterial() == 0) {
            new Thread(() -> {
                pushOa(id);
            }).start();
        } else {
            UpdateWrapper<ContractAudit> uw = new UpdateWrapper<>();
            uw.lambda().set(ContractAudit::getContractStatus, ContractAuditStatusEnum.OA_SUCCESS.getCode())
                    .set(ContractAudit::getOaMsg, "补充物料编码无需OA审批")
                    .eq(ContractAudit::getId, id);
            contractAuditService.updateEntity(uw);
        }
        return JsonResult.OK();
    }

    /**
     * 合同历史
     *
     * @param contractAuditVO
     * @return
     */
    @GetMapping("/history")
    public JsonResult<?> history(ContractAuditVO contractAuditVO) {
        List<ContractAuditVO> contractAuditHistoryList = contractAuditService.getContractAuditHistory(contractAuditVO);
        return JsonResult.OK(contractAuditHistoryList);
    }

    /**
     * 暂存合同取消评审
     *
     * @param contractAuditCancelVO
     * @return
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/save-cancel")
    public JsonResult<?> saveContractAuditCancel(@RequestBody ContractAuditCancelVO contractAuditCancelVO) {
        contractAuditService.saveContractAuditCancel(contractAuditCancelVO);
        return JsonResult.OK();
    }

    /**
     * 删除合同取消评审
     *
     * @param contractAuditId
     * @return
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/delete-cancel/{contractAuditId}")
    public JsonResult<?> deleteContractAuditCancel(@PathVariable("contractAuditId") String contractAuditId) {
        contractAuditService.deleteContractAuditCancel(contractAuditId);
        return JsonResult.OK();
    }

    /**
     * 提交合同取消评审
     *
     * @param contractAuditCancelVO
     * @return
     */
    @Log(operation = PermissionCons.CONTRACT_CANCEL_LABEL)
    @BindPermission(name = PermissionCons.CONTRACT_CANCEL_LABEL, code = PermissionCons.CONTRACT_CANCEL)
    @PostMapping("/submit-cancel")
    public JsonResult<?> submitContractAuditCancel(@RequestBody ContractAuditCancelVO contractAuditCancelVO) throws Exception {
        String contractAuditId = contractAuditCancelVO.getContractAuditId();
        ContractAuditVO contractAuditVO = contractAuditService.getViewObject(contractAuditId, ContractAuditVO.class);
        if (contractAuditVO.getContractProductVOList() == null) {
            return JsonResult.FAIL_VALIDATION("合同产品不能为空");
        }
        if (contractAuditVO.getContractProductVOList().stream().anyMatch(e -> S.equals(e.getSapContractPushStatus(), "1") && S.isNotBlank(e.getSapContractCode())) && S.equals(contractAuditVO.getSapStatus(), SAPStatusEnum.NO.getCode())) {
            return JsonResult.FAIL_VALIDATION("请先将合同变更推送到SAP");
        }
        String id = contractAuditService.submitContractAuditCancel(contractAuditCancelVO);
        ContractAudit contractAudit = this.getEntity(id);
        if (!contractAudit.getIsAudit()) {
            contractAudit.setContractStatus(ContractAuditStatusEnum.SUPPLEMENTARY_TECHNOLOGY_LIST.getCode());
            contractAuditService.updateEntity(contractAudit);
            return JsonResult.OK();
        }
        new Thread(() -> {
            pushOa(id);
        }).start();
        return JsonResult.OK();
    }

    //----------------------------------低代码生成----------------------------------//


    /**
     * 查询资源对象的列表VO记录
     * <p>
     * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<ContractAuditListVO>> getListVOMapping(ContractAuditDTO queryDto, Pagination pagination) throws Exception {
        return super.getViewObjectList(queryDto, pagination, ContractAuditListVO.class);
    }

    /**
     * 根据id查询资源对象的详情VO
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<ContractAuditDetailVO> getDetailVOMapping(@PathVariable("id") String id) throws Exception {
        ContractAuditDetailVO detailVO = contractAuditService.getViewObject(id, ContractAuditDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
     * 创建资源对象数据
     *
     * @param contractAudit
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<?> createModelMapping(@RequestBody ContractAudit contractAudit) throws Exception {
        boolean success = contractAuditService.createEntity(contractAudit);
        log.debug("新建数据 合同审批:{} {}", contractAudit.getId(), success ? "成功" : "失败");
        return JsonResult.OK(contractAudit.getId());
    }

    /**
     * 批量创建资源对象数据
     *
     * @param contractAuditList
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch")
    public JsonResult<?> batchCreateModelMapping(@RequestBody List<ContractAudit> contractAuditList) throws Exception {
        boolean success = contractAuditService.createEntities(contractAuditList);
        log.debug("批量新建数据 合同审批 {}", success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id更新资源对象
     *
     * @param contractAudit
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id") String id, @RequestBody ContractAudit contractAudit) throws Exception {
        boolean success = contractAuditService.updateEntity(contractAudit);
        log.debug("更新数据 合同审批:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = contractAuditService.deleteEntity(id);
        log.debug("删除数据 合同审批:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据ids集合删除资源对象
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = contractAuditService.deleteEntities(ids);
        log.debug("批量删除数据 合同审批:{} {}", ids, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 对比物料
     *
     * @param param
     * @return
     * @throws Exception
     * @author 陈广煜
     * @date 2024-08-20
     */
    @Log(operation = OperationCons.LABEL_READ)
    @BindPermission(name = OperationCons.LABEL_READ, code = OperationCons.CODE_READ)
    @PostMapping("/compareMrl")
    public JsonResult<?> compareMrl(@RequestBody Map<String, Object> param) {
        List<Map<String, Object>> mrlList = (List<Map<String, Object>>) param.get("mrlList");
        List<ContractProductMaterialVO> list = BeanUtils.convertMap2BeanList(mrlList, ContractProductMaterialVO.class);
        List<ContractProductMaterialVO> contractProductMaterialVOS = contractAuditService.compareMaterial((String) param.get("sapNo"), (String) param.get("salesOrg"), list);
        return JsonResult.OK(contractProductMaterialVOS);
    }

    /**
     * 推送OA
     *
     * @param id
     * @author 陈广煜
     * @date 2024-09-10
     */
    @Transactional
    public void pushOa(String id) {
        String msg;
        String res = OAStatusEnum.SUCCESS.getCode();
        String contractStatus = ContractAuditStatusEnum.OA_PROCESSING.getCode();
        try {
            MultiValueMap<String, Object> requestParam = oaInterfaceService.getRequestParam(id);
            // OA推送
            String url = "/api/km-review/kmReviewRestService/addReview";
            msg = oaInterfaceService.accessOaInterface(url, requestParam);
            if (S.equals(msg, "user is not exist")) {
                res = OAStatusEnum.FAIL.getCode();
                contractStatus = ContractAuditStatusEnum.NO_SUBMIT.getCode();
                msg = "推送失败，" + msg;
            } else {
                // 推送完成后，更新合同项目sap推送状态
                UpdateWrapper<ContractProduct> uw = new UpdateWrapper<>();
                uw.lambda().set(ContractProduct::getSapContractPushStatus, "1").eq(ContractProduct::getContractAuditId, id);
                contractProductService.updateEntity(uw);
                // 更新sap合同关联字段
                salesContractService.updateRelatedField(id);
            }
        } catch (Exception e) {
            msg = "推送失败，系统错误";
            log.error("OA推送失败", e);
            res = OAStatusEnum.FAIL.getCode();
            ContractAudit contract = contractAuditService.getEntity(id);
            if (S.equals(ContractAuditTypeEnum.CREATE.getCode(), contract.getAuditType())) {
                contractStatus = ContractAuditStatusEnum.NO_SUBMIT.getCode();
            }
            if (S.equals(ContractAuditTypeEnum.CANCEL.getCode(), contract.getAuditType())){ // 如果是取消合同，推送失败，则回退合同状态
                contractStatus = ContractAuditStatusEnum.OA_SUCCESS.getCode();
            }
            // 如果是更新合同，推送失败，则回退合同状态
            if (S.equals(ContractAuditTypeEnum.UPDATE.getCode(), contract.getAuditType())) {
                contractStatus = ContractAuditStatusEnum.NO_SUBMIT.getCode();
                UpdateWrapper<ContractAudit> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().set(ContractAudit::getContractStatus, ContractAuditStatusEnum.OA_SUCCESS.getCode())
                        .set(ContractAudit::getOaStatus, OAStatusEnum.FAIL.getCode())
                        .set(ContractAudit::getOaMsg, "合同变更OA推送失败：" + msg)
                        .eq(ContractAudit::getContractCode, contract.getContractCode())
                        .eq(ContractAudit::getContractVersion, contract.getContractVersion() - 1);
                contractAuditService.updateEntity(updateWrapper);
            }
        }
        // 推送完成后，获取响应结果，变更合同审批状态
        UpdateWrapper<ContractAudit> uw = new UpdateWrapper<>();
        uw.lambda().set(ContractAudit::getContractStatus, contractStatus).set(ContractAudit::getOaMsg, msg)
                .set(ContractAudit::getOaStatus, res).eq(ContractAudit::getId, id);
        contractAuditService.updateEntity(uw);
    }


    /**
     * 关注或取关
     *
     * @return
     * @author 陈广煜
     * @date 2024-09-19
     */
    @Log(operation = OperationCons.LABEL_WRITE)
    @BindPermission(name = OperationCons.LABEL_WRITE, code = OperationCons.CODE_WRITE)
    @PostMapping("/starOrCancel")
    public JsonResult<String> star(String id) throws Exception {
        ContractAuditListVO contract = contractAuditService.getViewObject(id, ContractAuditListVO.class);
        List<String> starUids = contract.getStarUids() == null ? new ArrayList<>() : contract.getStarUids();
        String userId = IamSecurityUtils.getCurrentUserId();
        // 取关
        if (starUids.contains(userId)) {
            starUids.remove(userId);
        } else {
            starUids.add(userId);
        }
        contract.setStarUids(starUids);
        contractAuditService.updateEntity(contract);
        return JsonResult.OK();
    }

    /**
     * 获取sap物料详情
     *
     * @param mrlCode  物料编码
     * @param salesOrg 销售组织
     * @param sapNo    sap客户号
     * @return
     */
    @Log(operation = OperationCons.LABEL_READ)
    @BindPermission(name = OperationCons.LABEL_READ, code = OperationCons.CODE_READ)
    @GetMapping("/getSapMrlDetail")
    public JsonResult<?> getSapMrlDetail(String mrlCode, String salesOrg, String sapNo, Pagination pagination) {
        List<Map<String, String>> sapMrlDetail = contractAuditService.getSapMrlList(mrlCode, salesOrg, sapNo, pagination);
        return JsonResult.OK(sapMrlDetail).bindPagination(pagination);
    }

    /**
     * 打印word
     *
     * @param response
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_READ)
    @BindPermission(name = OperationCons.LABEL_READ, code = OperationCons.CODE_READ)
    @GetMapping("/printWord/{id}")
    public JsonResult<?> printWord(HttpServletResponse response, @PathVariable("id") String id) throws Exception {
        String filePath = contractAuditService.printWord(id);
        File file = new File(filePath);
        if (!file.exists()) {
            return JsonResult.FAIL_OPERATION("文件不存在");
        }
        HttpHelper.downloadLocalFile(file, file.getName(), response);
        return null;
    }

    /**
     * 补充技术清单
     *
     * @param contractProductListVO
     * @return
     */
    @PostMapping("/addTechList")
    public JsonResult<?> addTechList(@RequestBody ContractProductListVO contractProductListVO) {
        if (contractProductListVO.getContractProductMaterialVOList() == null || contractProductListVO.getContractProductMaterialVOList().size() == 0) {
            return JsonResult.FAIL_OPERATION("请添加技术清单");
        }
        contractAuditService.addTechList(contractProductListVO);
        return JsonResult.OK();
    }

    /**
     * 获取sap库存
     *
     * @param mrlList
     * @return
     * @throws Exception
     */
    @PostMapping("/getSapInventory")
    public JsonResult<?> getSapInventory(@RequestBody List<ContractProductMaterial> mrlList) throws Exception {
        Map<String, String> map = contractAuditService.getSapInventory(mrlList);
        return JsonResult.OK(map);
    }
}
